
<template>
  <div id="map">
    <div style="position: fixed; top: 100px; right: 50px; z-index: 999">
      <el-button type="primary"  @click="drawFeature('Point')">画点</el-button>

      <el-button type="primary" v-if="lineButton" @click="drawFeature('LineString')"
        >画线</el-button
      >
      <el-button type="primary" v-if="areaButton" @click="drawFeature('Polygon')">画面</el-button>
      <!-- <el-button type="primary" v-show="false" @click="drawFeature('Circle')"
        >画圆</el-button
      > -->
      <!-- <el-button type="primary" @click="draw.removeLastPoint()">撤回</el-button> -->
      <el-button type="primary" @click="map.removeInteraction(draw)"
        >取消</el-button
      >
      <el-button type="danger" @click="clearDrawLayer()">清除</el-button>

      <el-button type="warning" @click="confirmFeature">确认</el-button>
    </div>
    
  </div>
</template>
<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import { Vector as VectorLayer } from "ol/layer";
import XYZ from "ol/source/XYZ";
import { OSM, Vector as VectorSource } from "ol/source";
import Draw from "ol/interaction/Draw";
import { Fill, Stroke, Style, Text, Icon,Circle } from "ol/style";
import { Feature } from "ol";
import { Polygon, Point } from "ol/geom";
export default {
  name: "MapTools",
  props: {
    value: {
      type: String,
      required: false,
    },
    mapColumnValue: {
      type: String,
      default: null,
    },
    mapColumn: {
      type: String,
      default: null,
    },
    mapColumnType: {
      type: String,
      default: null,
    },
    center: {
      type: String,
      required: false,
    },
    mapType: {
      type: String,
      required: false,
    },
    geomValue: {
      type: String,
      required: false,
    },
  },
  data() {
    return {
      map: {},
      draw_source: new VectorSource(),
      draw_vector:null,
      draw: {},
      currentValue: "",
      drawType: null,
      currentCenter: "",
      currentGeom: "",
      currentFeature: null,
      mapGeomInfo: "",
      positionVectorLayer: null,
      ponitButton:false,
      areaButton:false,
      lineButton:false
    };
  },

  watch: {
    value(value) {
      // 父组件收到input事件后会通过v-model改变value参数的值
      // 然后此处会watch到value的改变，发出change事件
      // change事件放在此处发射的好处是，当外部修改value值时，也能够触发form-data-change事件
      this.$emit("change", value);
      console.log("geom:" + value);
      if (this.currentValue === value) {
        return;
      }
    },
  },

  mounted() {
    console.log("从maplonlat组建获取:" + this.geomValue);
    this.initMap();
    this.addDrawLayer();
    console.log("mapColumnType:" + this.mapColumnType);
    if(this.mapColumnType=="point"){
      this.ponitButton=true;
    }
    if(this.mapColumnType=="geom"){
      this.areaButton=true;
    }
  },
  updated() {
    console.log("App.vue finish re-render");
  },
  methods: {
    clearFeature() {
      this.$emit("drawEnd", "");
      this.feature = null;
    },
    //确认
    confirmFeature(layer) {
      if (this.currentCenter == null && this.currentGeom == null) {
        this.$message({
          message: "您还未选择数据",
          type: "warning",
        });
        return;
      }
      //向父组件传值
      this.$emit(
        "drawEnd",
        JSON.stringify({ center: this.currentCenter, geom: this.currentGeom })
      );
    },
    //添加绘制点线面图层
    addDrawLayer() {
      this.draw_vector = new VectorLayer({
        source: this.draw_source,
        //绘制好后，在地图上呈现的样式
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.6)",
          }),
          stroke: new Stroke({
            //边界样式
            color: "#ffcc33",
            width: 3,
          }),
          //点样式继承image
          image: new Circle({
            radius: 7,
            fill: new Fill({
              color: "#ffcc33",
            }),
          }),
        }),
      });
      this.map.addLayer(this.draw_vector);
      this.loadGeom();
    },
    //加载当前配置
    loadGeom() {
      console.log("geomValue:"+this.geomValue);
      if (this.geomValue) {
        let mapGeom = JSON.parse(this.geomValue);
        if(!mapGeom.center) return;
        let feature = [];
        const iconStyle = new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.6)",
          }),
          stroke: new Stroke({
            //边界样式
            color: "#ffcc33",
            width: 3,
          }),
          //点样式继承image
          image: new Icon({
                scale: 1,
                size: [52, 72],
                anchor: [0.5, 1],
                src: "/image/icon/map/default.png",
              }),
        });

        //点位
        let ponitFeature = new Feature({
          geometry: new Point(JSON.parse(mapGeom.center)),
        });
        ponitFeature.setStyle(iconStyle);
        feature.push(ponitFeature);
        //多边形
        if(mapGeom.geom!=""){
          let polygonFeature = new Feature({
          geometry: new Polygon(JSON.parse(mapGeom.geom)),
          });
          polygonFeature.setStyle(iconStyle);
          feature.push(polygonFeature);
        }
        

        

        let vectorSource = new VectorSource({
          features: feature,
        });
        this.positionVectorLayer = new VectorLayer({
          source: vectorSource,
        });
        this.map.addLayer(this.positionVectorLayer);
      }
    },
    //清除绘制图层
    clearDrawLayer() {
      this.map.removeInteraction(this.draw); //移除交互
      if(this.draw_vector) this.draw_vector.getSource().clear(); //清除图层上的所有要素
       if(this.positionVectorLayer) this.positionVectorLayer.getSource().clear();
    },
    //绘制点线面
    drawFeature(featureType = "") {
      this.clearDrawLayer();
      this.map.removeInteraction(this.draw);
      this.drawType = featureType;
      this.draw = new Draw({
        source: this.draw_source,
        type: featureType,
        //绘制时，在地图上呈现的样式
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.6)",
          }),
          stroke: new Stroke({
            color: "#ffcc33",
            width: 2,
          }),
          image: new Circle({
            radius: 7,
            fill: new Fill({
              color: "#ffcc33",
            }),
          }),
        }),
      });
      this.draw.on("drawstart", function (evt) {
        //逻辑代码
      });
      let that = this;
      this.draw.on("drawend", (evt) => {
        let geometry = evt.feature.getGeometry();
        let coordinate = geometry.getCoordinates();
        console.log("coordinate:" + coordinate);
        let curCenter = null;
        let geom = null;
        console.log("featureType:" + featureType);
        if (featureType == "Point") {
          this.currentFeature = JSON.stringify(coordinate);
          this.currentCenter = curCenter = this.currentFeature;
        } else if (featureType === "Polygon") {
          var polygon = new Polygon(coordinate);
          let curCenters = polygon.getInteriorPoint().getCoordinates();
          curCenter = "[" + curCenters[0] + "," + curCenters[1] + "]";

          geom = JSON.stringify(coordinate);
        } else if (featureType === "LineString") {
          var polygon = new Polygon(coordinate);
          geom = JSON.stringify(coordinate);
        } else if (featureType === "Circle") {
        }
        this.currentCenter = curCenter;
        this.currentGeom = geom;
        // that.$emit(
        //   "drawEnd",
        //   JSON.stringify({ center: curCenter, geom: geom })
        // );
        this.map.removeInteraction(that.draw);
      });
      this.map.addInteraction(this.draw);
    },
    // 初始化地图
    initMap() {
      this.map = new Map({
        target: "map",
        layers: [
          new TileLayer({
            visible: true,
            source: new XYZ({
              visible: true,
              url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
            }),
          }),
        ],
        view: new View({
          projection: "EPSG:4326",
          center: [114.06124090060078, 22.547329337182056],
          zoom: 12, //默认缩放级别
          minZoom: 1, //最小缩放级别
          maxZoom: 18, //最大缩放级别
        }),
      });
      console.log("mapColumnValue:"+this.mapColumnValue)
    },
  },
};
</script>
<style scoped>
#map {
  width: 100%;
  height: 100%;
  position: absolute;
}
</style>